<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'rd:rd10:m8Rd10:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #m8Rds10List>
        <BasicTable
          @register="registerM8Rds10Table"
          @row-click="handleM8Rds10RowClick"
        />
        <!-- <a-button class="mt-2" @click="handleM8Rds10Add" v-auth="'rd:rd10:m8Rd10:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsM8RdRd10M8Rd10Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { M8Rd10, m8Rd10Save, m8Rd10Form } from '/@/api/m8/rd/rd10/m8Rd10';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('m8.rd.rd10.m8Rd10');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<M8Rd10>({} as M8Rd10);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增产品入库单') : t('编辑产品入库单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('单据号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
    },
    // {
    //   label: t('业务类型'),
    //   field: 'busType',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'sc_bus_type',
    //     allowClear: true,
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: t('制单时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('修改时间'),
      field: 'updateDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
    },
    {
      label: t('修改人'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: true,
    },
    {
      label: t('单据状态'),
      field: 'djStatus',
      component: 'Select',
      componentProps: {
        dictType: 'dj_status',
        allowClear: true,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据来源'),
      field: 'csource',
      component: 'Select',
      componentProps: {
        dictType: 'm8_rd10_source',
        allowClear: true,
      },
      dynamicDisabled: true,
    },
    {
      label: t('产品入库明细'),
      field: 'm8Rds10List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'm8Rds10List',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
    
  });

  const [registerM8Rds10Table, m8Rds10Table] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'i-ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleM8Rds10Delete.bind(this, record),
    //       },
    //       auth: 'rd:rd10:m8Rd10:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setM8Rds10TableData(_res: Recordable) {
    m8Rds10Table.setColumns([
      {
        title: t('图纸ID'),
        dataIndex: 'picId',
        width: 130,
        align: 'left',
        ifShow: false,
      },
      {
        title: t('图名'),
        dataIndex: 'picName',
        width: 160,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 200,
        // },
        // editRule: true,
      },
      {
        title: t('客户'),
        dataIndex: 'cusCode',
        width: 120,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 64,
        // },
        // editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 100,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 16,
        // },
        // editRule: false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 140,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
      {
        title: t('行状态'),
        dataIndex: 'rowStatus',
        width: 100,
        align: 'center',
        dictType: 'dj_row_status',
        // editRow: true,
        // editComponent: 'Select',
        // editComponentProps: {
        //   dictType: 'dj_row_status',
        //   allowClear: true,
        // },
        // editRule: false,
      },
    ]);
    m8Rds10Table.setTableData(record.value.m8Rds10List || []);
  }

  function handleM8Rds10RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleM8Rds10Add() {
    m8Rds10Table.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleM8Rds10Delete(record: Recordable) {
    m8Rds10Table.deleteTableDataRecord(record);
  }

  async function getM8Rds10List() {
    let m8Rds10ListValid = true;
    let m8Rds10List: Recordable[] = [];
    for (const record of m8Rds10Table.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        m8Rds10ListValid = false;
      }
      m8Rds10List.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of m8Rds10Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      m8Rds10List.push({
        ...record,
        status: '1',
      });
    }
    if (!m8Rds10ListValid) {
      throw { errorFields: [{ name: ['m8Rds10List'] }] };
    }
    return m8Rds10List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await m8Rd10Form(data);
    record.value = (res.m8Rd10 || {}) as M8Rd10;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setM8Rds10TableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.m8Rds10List = await getM8Rds10List();
      // console.log('submit', params, data, record);
      const res = await m8Rd10Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
